package smartcampus.scjava.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import smartcampus.scjava.POJO.DTO.SmartuserDTO;
import smartcampus.scjava.custom.ResultVO;
import smartcampus.scjava.service.SmartuserService;

import javax.annotation.Resource;

/**
 * @author 北煜
 */
@Api(tags = "用户管理")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    SmartuserService smartuserService;

    @GetMapping("/show/getUserByUsername/{username}")
    @ApiOperation("根据用户名查找用户")
    public ResultVO<SmartuserDTO> getUserByUsername(@PathVariable String username) {
        SmartuserDTO userDTO = smartuserService.getUserByUsername(username);
        return ResultVO.success(userDTO);
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public ResultVO<String> login(@RequestBody SmartuserDTO smartuserDTO) {
        String result = smartuserService.checkLogin(smartuserDTO.getUsername(), smartuserDTO.getPassword());
        if (result.length() > 20) {
            return ResultVO.success("登录成功",result);
        }
        return ResultVO.success(result);
    }

    @PostMapping("/register")
    @ApiOperation("注册")
    public ResultVO<?> register(@RequestBody SmartuserDTO smartuserDTO){
        SmartuserDTO user = smartuserService.getUserByUsername(smartuserDTO.getUsername());
        if (user !=  null) {
            return ResultVO.error("用户名已存在,注册失败，请重试！");
        }
        Long result = smartuserService.register(smartuserDTO.getUsername(), smartuserDTO.getPassword());
        if (result != null){
            return ResultVO.success("注册成功");
        } else if (result == 0L) {
            return ResultVO.error("注册失败,请重试");
        } else if (result == -1L) {
            log.error("注册失败,数据库回滚错误，检查用户表");
            return ResultVO.error("注册失败,系统错误");
        }
        return ResultVO.error("注册失败，请重试！");
    }
}
